package Manage;

import Change.ChangeInfo;
import Change.ChangePassword;
import EncapsulatingObjects.Trip;
import EncapsulatingObjects.User;
import LoginSystem.LoginPage;
import TextDocument.UserAgreement;
import Util.ShoppingCartUtil;
import Util.TripDatabaseUtil;
import Util.UiUtil;
import Util.UserDatabaseUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class ViewAllTrip {
    protected static JFrame jf;
    protected static JTable table;
    protected static JScrollPane sp;

    JMenuBar jb;
    JMenu home;
    JMenu mUser;
    JMenu help;

    JMenuItem myHome;
    JMenuItem cInfo;
    JMenuItem cPass;
    JMenuItem mlogout;

    protected static JButton OK;
    protected static JButton CANCEL;
    protected static JPopupMenu rightClick;
    public static String buttonName = "OK";
    boolean statue;
    TripDatabaseUtil td = new TripDatabaseUtil();
    UserDatabaseUtil ud = new UserDatabaseUtil();
    ShoppingCartUtil su = new ShoppingCartUtil();
    static ArrayList<String> columns;
    static String[] columnCount;
    List<Trip> trips = new ArrayList<>();
    User currentUser = new User();

    public ViewAllTrip() {
        init();
        columns = td.getColumn();
        columnCount = new String[columns.size()];

        for (int i = 0; i < columns.size(); i++) {
            columnCount[i] = columns.get(i);
        }

        viewAll();

        UiUtil.setFrameCenter(jf);
        jf.setVisible(true);
    }

    void init() {
        jf = new JFrame("Manage");
        jf.setSize(1175, 740);
        jf.setLayout(null);
        isAdmin();
        ud.initUser(currentUser);

        jf.setResizable(false);
        sp = new JScrollPane();
        sp.setBounds(30, 35, 1100, 600);
        jf.add(sp);

        jb = new JMenuBar();
        home = new JMenu("View All Trip");

        mUser = new JMenu("User");
        help = new JMenu("Help Me");
        help.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                UserAgreement.isHelp = true;
                new UserAgreement();
            }
        });

        myHome = new JMenuItem("My Homepage");
        myHome.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jf.dispose();
            }
        });

        cInfo = new JMenuItem("Change Information");
        cInfo.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                new ChangeInfo();
            }
        });
        cPass = new JMenuItem("Change Password");
        cPass.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                new ChangePassword();
            }
        });
        mlogout = new JMenuItem("Log Out");
        mlogout.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                logout();
            }
        });

        jb.setBackground(Color.LIGHT_GRAY);
        jb.setBounds(0, 0, 1175, 32);

        jb.add(home);
        jb.add(mUser);
        //jb.add(shopCar);
        jb.add(help);

        mUser.add(myHome);
        mUser.add(cInfo);
        mUser.add(cPass);
        mUser.add(mlogout);

        jf.add(jb);

        rightClick = new JPopupMenu();
        JMenuItem fresh = new JMenuItem();
        fresh.setText("  FRESH  ");
        fresh.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                viewAll();
            }
        });
        JMenuItem radd = new JMenuItem();
        radd.setText("  Add New Trip  ");
        radd.addActionListener(new ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addTrip();
            }
        });
        JMenuItem rupdate = new JMenuItem();
        rupdate.setText("  Update the Trip  ");
        rupdate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                update();
            }
        });
        JMenuItem rdelete = new JMenuItem();
        rdelete.setText("  Delete the Trip  ");
        rdelete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                remove();
            }
        });

        JMenuItem rPay = new JMenuItem();
        rPay.setText("  Place order    ");
        rPay.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                pay();
            }
        });
        JMenuItem rDeleteFromCart = new JMenuItem();
        rDeleteFromCart.setText("  Remove from cart    ");
        rDeleteFromCart.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                removeFromCart();
            }
        });

        rightClick.add(fresh);
        if (statue) {
            rightClick.add(radd);
            rightClick.add(rupdate);
            rightClick.add(rdelete);
        } else {
            if(!buttonName.equals("Refresh")) {
                rightClick.add(rPay);
                rightClick.add(rDeleteFromCart);
            }
        }

        table = new JTable();
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                tableMouseClicked(e);
            }
        });

        table.setDefaultRenderer(Object.class, new TableCellTextAreaRenderer());

        sp.setViewportView(table);

        OK = new JButton();
        OK.setText(buttonName);
        OK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                switch (buttonName) {
                    case "View all trip":
                        viewAll();
                        break;
                    case "Add trip":
                        addTrip();
                        break;
                    case "Change trip":
                        update();
                        break;
                    case "Delete trip":
                        remove();
                        break;
                    case "Submit":
                        pay();
                        break;
                }
            }
        });
        OK.setBounds(850, 650, 150, 30);
        OK.setOpaque(true);
        OK.setBackground(Color.CYAN);
        jf.add(OK);

        CANCEL = new JButton("CLOSE");
        CANCEL.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jf.dispose();
            }
        });
        CANCEL.setBounds(1030, 650, 100, 30);
        CANCEL.setOpaque(true);
        CANCEL.setBackground(Color.lightGray);
        jf.add(CANCEL);
    }

    private void removeFromCart() {
        ShoppingCartUtil su = new ShoppingCartUtil();
        su.updateTripToCart(currentUser, trips.get(table.getSelectedRow()), 1);
        JOptionPane.showMessageDialog(jf, "Successfully removed from cart!");
        viewAll();
    }

    private void pay() {
        ShoppingCartUtil su = new ShoppingCartUtil();
        su.updateTripToCart(currentUser, trips.get(table.getSelectedRow()), 3);
        JOptionPane.showMessageDialog(jf, "Payment successful!");
        viewAll();
    }

    private void logout() {
        if (JOptionPane.showConfirmDialog(jf, "Are you sure you want to log out") == JOptionPane.YES_OPTION) {
            User user = new User();
            UserDatabaseUtil du = new UserDatabaseUtil();
            du.initUser(user);
            du.updateLoginStatue(user, false);
            jf.dispose();
            new LoginPage();
        }
    }

    private void addTrip() {
        AddUpdate.isAdd = true;
        new AddUpdate();
    }

    private void tableMouseClicked(MouseEvent e) {
        mouseRightButtonClick(e);
    }

    private void mouseRightButtonClick(java.awt.event.MouseEvent evt) {
        //判断是否为鼠标的BUTTON3按钮，BUTTON3为鼠标右键
        if (evt.getButton() == MouseEvent.BUTTON3) {
            //通过点击位置找到点击为表格中的行
            int focusedRowIndex = table.rowAtPoint(evt.getPoint());
            if (focusedRowIndex == -1) {
                return;
            }
            //将表格所选项设为当前右键点击的行
            table.setRowSelectionInterval(focusedRowIndex, focusedRowIndex);
            //弹出菜单
            rightClick.show(table, evt.getX(), evt.getY());
        }
    }

    private void viewAll() {
        if (buttonName.equals("Submit")) {
            trips.clear();
            trips = td.quaryAll(su.viewMyCart(currentUser, 2));
        } else if (buttonName.equals("Refresh")) {
            trips.clear();
            trips = td.quaryAll(su.viewMyCart(currentUser, 3));
        } else{
            trips.clear();
            trips = td.quaryAll();
        }

        Object[][] data = new Object[trips.size()][];
        for (int i = 0; i < trips.size(); i++) {
            Trip t = trips.get(i);
            Object[] info = new Object[]{t.getId(), t.getName(), t.getsPosition(), t.getePosition(),
                    t.getsDate(), t.geteDate(), t.getHotelNamex(), t.getDoWhat(), t.getMoney(),};
            data[i] = info;
        }
        table.setModel(new DefaultTableModel(data, columnCount));
    }

    private void remove() {
        int i = table.getSelectedRow();
        if (i < 0) {
            JOptionPane.showMessageDialog(jf, "Please select a row!");
            return;
        }
        Trip t = trips.get(i);
        ShoppingCartUtil su = new ShoppingCartUtil();
        su.getTripId(t);
        su.dropTrip(t);
        td.delete(t.getId());
        viewAll();
    }

    private void update() {
        int i = table.getSelectedRow();
        if (i < 0) {
            JOptionPane.showMessageDialog(jf, "Please select a row!");
            return;
        }
        AddUpdate.trip = trips.get(i);
        AddUpdate.isAdd = false;
        new AddUpdate();
    }

    public void isAdmin() {
        UserDatabaseUtil ud = new UserDatabaseUtil();
        try {
            Connection conn = ud.getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from userdata");
            while (rs.next()) {
                if (rs.getBoolean("isLogin") == true) {
                    statue = rs.getBoolean("isAdmin");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



class TableCellTextAreaRenderer extends JTextArea implements TableCellRenderer {
    public TableCellTextAreaRenderer() {
        setLineWrap(true);
        setWrapStyleWord(true);

    }

    public Component getTableCellRendererComponent(JTable table, Object value,
                                                   boolean isSelected, boolean hasFocus, int row, int column) {
        int maxPreferredHeight = 0;
        for (int i = 0; i < table.getColumnCount(); i++) {
            setText("" + table.getValueAt(row, i));
            setSize(table.getColumnModel().getColumn(column).getWidth(), 0);
            maxPreferredHeight = Math.max(maxPreferredHeight, getPreferredSize().height);
        }

        if (table.getRowHeight(row) != maxPreferredHeight)
            table.setRowHeight(row, maxPreferredHeight);

        setText(value == null ? "" : value.toString());
        return this;
    }
}